package online.inote.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * <p>
 * Desc:
 * </p>
 *
 * @author XQF SUI
 * @created 2018年8月25日 下午8:21:23
 * @version 1.0
 */
public class SerializableUtils {

	public static byte[] serializable(Object object) {
		byte[] result = null;

		if (object == null) {
			return new byte[0];
		}

		try {
			ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);

			try {
				if (!(object instanceof Serializable)) {
					throw new IllegalArgumentException(
							SerializableUtils.class.getSimpleName() + " requires a Serializable payload "
									+ "but received an object of type [" + object.getClass().getName() + "]");
				}

				ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
				objectOutputStream.writeObject(object);
				objectOutputStream.flush();
				result = byteStream.toByteArray();
			} catch (Throwable ex) {
				throw new Exception("Failed to serialize", ex);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return result;
	}
}